import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { DepartmentItem } from "@/components/DepartmentTree/types";

// 定义任务信息的类型
export interface TaskInfo {
  missionCode: string
  name: string
  superiorExportTime: string
  // 根据实际接口返回的字段添加其他属性
  [key: string]: any
}

export const useDeviceTreeStore = defineStore('deviceTree', () => {
  const currentDepartment = ref('')
  const currentNodeKey = ref('')
  const currentTreeNode = ref<DepartmentItem | null>(null)
  const taskInfo = ref<TaskInfo | null>(null) // 新增任务信息
  const currentTask = ref('') // 新增当前任务代码
  const departmentList = ref<DepartmentItem[]>([]) // 新增：存储整个设备树数据
  const deviceNameCache = ref(new Map<string, string>()) // 新增：设备名称缓存

  // 从localStorage恢复状态
  const loadState = () => {
    const saved = localStorage.getItem('deviceTreeState')
    if (saved) {
      const state = JSON.parse(saved)
      currentDepartment.value = state.currentDepartment || ''
      currentNodeKey.value = state.currentNodeKey || ''
      currentTask.value = state.currentTask || '' // 恢复当前任务

      // 恢复节点数据
      if (state.currentTreeNode) {
        currentTreeNode.value = state.currentTreeNode
      }

      // 恢复任务信息
      if (state.taskInfo) {
        taskInfo.value = state.taskInfo
      }
    }
  }

  // 保存状态到localStorage
  const saveState = () => {
    const state = {
      currentDepartment: currentDepartment.value,
      currentNodeKey: currentNodeKey.value,
      currentTreeNode: currentTreeNode.value,
      currentTask: currentTask.value, // 保存当前任务
      taskInfo: taskInfo.value // 保存任务信息
    }
    localStorage.setItem('deviceTreeState', JSON.stringify(state))
  }

  // 设置当前节点
  const setCurrentNode = (node: DepartmentItem | null) => {
    currentTreeNode.value = node
    currentNodeKey.value = node?.deviceCode || ''
    saveState()
  }

  // 设置当前根节点
  const setCurrentDepartment = (departmentCode: string) => {
    currentDepartment.value = departmentCode
    saveState()
  }

  // 设置任务信息 - 新增方法
  const setTaskInfo = (task: TaskInfo | null) => {
    taskInfo.value = task
    currentTask.value = task?.missionCode || ''
    saveState()
  }

  // 设置当前任务代码 - 新增方法
  const setCurrentTask = (taskCode: string) => {
    currentTask.value = taskCode
    saveState()
  }

  // 设置设备树数据 - 新增方法
  const setDepartmentList = (list: DepartmentItem[]) => {
    departmentList.value = list
    // 清空缓存，因为树结构可能发生了变化
    deviceNameCache.value.clear()
  }

  /**
   * 根据设备编码获取设备名称
   * @param deviceCode 设备编码
   * @returns 设备名称
   */
  const getDeviceNameByCode = (deviceCode: string): string => {
    if (!deviceCode) return ''

    // 检查缓存
    if (deviceNameCache.value.has(deviceCode)) {
      return deviceNameCache.value.get(deviceCode)!
    }

    // 递归查找设备节点
    const findNode = (nodes: any[], code: string): any => {
      if (!nodes || !Array.isArray(nodes)) return null

      for (const node of nodes) {
        if (node.deviceCode === code) {
          return node
        }
        if (node.children && Array.isArray(node.children)) {
          const found = findNode(node.children, code)
          if (found) return found
        }
      }
      return null
    }

    let deviceNode = null

    // 1. 先在整个设备树中查找
    if (departmentList.value && departmentList.value.length > 0) {
      deviceNode = findNode(departmentList.value, deviceCode)
    }

    // 2. 如果没找到，尝试在当前节点及其子节点中查找
    if (!deviceNode && currentTreeNode.value) {
      deviceNode = findNode([currentTreeNode.value], deviceCode)
    }

    const deviceName = deviceNode?.deviceName || '未知设备'

    // 存入缓存
    deviceNameCache.value.set(deviceCode, deviceName)
    return deviceName
  }

  /**
   * 清空设备名称缓存
   */
  const clearDeviceNameCache = (): void => {
    deviceNameCache.value.clear()
  }

  /**
   * 批量获取设备名称
   * @param deviceCodes 设备编码数组
   * @returns 设备名称映射对象
   */
  const getDeviceNamesByCodes = (deviceCodes: string[]): Record<string, string> => {
    const result: Record<string, string> = {}
    deviceCodes.forEach(code => {
      result[code] = getDeviceNameByCode(code)
    })
    return result
  }

  /**
   * 预加载设备名称缓存（性能优化）
   * @param nodes 设备树节点数组
   */
  const preloadDeviceNameCache = (nodes: DepartmentItem[]): void => {
    const loadNodes = (nodeList: DepartmentItem[]) => {
      nodeList.forEach(node => {
        if (node.deviceCode) {
          deviceNameCache.value.set(node.deviceCode, node.deviceName)
        }
        if (node.children && Array.isArray(node.children)) {
          loadNodes(node.children)
        }
      })
    }

    loadNodes(nodes)
  }

  // 清除状态
  const clearState = () => {
    currentDepartment.value = ''
    currentNodeKey.value = ''
    currentTreeNode.value = null
    taskInfo.value = null
    currentTask.value = ''
    departmentList.value = []
    deviceNameCache.value.clear()
    localStorage.removeItem('deviceTreeState')
  }

  // 初始化时加载状态
  loadState()

  return {
    currentDepartment,
    currentNodeKey,
    currentTreeNode,
    taskInfo,
    currentTask,
    departmentList, // 导出设备树数据
    deviceNameCache, // 导出缓存（可选，主要用于调试）

    setCurrentNode,
    setCurrentDepartment,
    setTaskInfo,
    setCurrentTask,
    setDepartmentList, // 导出设置设备树方法
    getDeviceNameByCode, // 导出设备名称查找方法
    getDeviceNamesByCodes, // 导出批量查找方法
    clearDeviceNameCache, // 导出清空缓存方法
    preloadDeviceNameCache, // 导出预加载方法
    loadState,
    saveState,
    clearState
  }
})
